<template>
  <div class="firmware-update-page pd16" v-loading="pageLoading">
    <el-row :gutter="16" class="flex-block">
      <el-col :span="6">
        <el-card class="box-card sp-card">
          <el-tree
            ref="treeRef"
            class="nr-tree"
            :data="treeData"
            :expand-on-click-node="false"
            show-checkbox
            default-expand-all
            node-key="pid"
            highlight-current
            :props="defaultProps"
          />
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card class="box-card sp-card">
          <div class="search-block">
            <el-form ref="searchParamsRef" :model="searchParams" @submit.prevent="search">
              <el-row :gutter="16">
                <el-col :span="6">
                  <el-form-item label="产品：" prop="product">
                    <el-select v-model="searchParams.product" clearable placeholder="请选择产品" style="width: 100%;" @change="handleChangeProduct">
                      <el-option
                        v-for="item in productOptions"
                        :key="item.productId"
                        :label="item.name"
                        :value="item.productId"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="当前版本：" prop="version">
                    <el-select v-model="searchParams.version" clearable placeholder="请选择固件版本" style="width: 100%;" @clear="handleClearVersion">
                      <el-option
                        v-for="item in versionOptions"
                        :key="item.id"
                        :label="item.firmwareName"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="设备搜索：" prop="device">
                    <el-input v-model="searchParams.device" clearable placeholder="请输入设备名称" style="width: 100%;"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item>
                    <el-button type="primary" @click="search">查询</el-button>
                    <el-button @click="reset">重置</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>

          <div class="btn-group">
            <el-button type="primary" @click="batchUpdate">批量升级</el-button>
          </div>

          <div ref="tableBlockRef" class="data-block mt16 table-block">
            <el-table ref="multipleTableRef" :data="tableData" :max-height="tableHeight" class="nr-table">
              <el-table-column type="selection" width="30"/>
              <el-table-column label="设备名称" prop="deviceName"></el-table-column>
              <el-table-column label="设备SN" prop="deviceSn"></el-table-column>
              <el-table-column label="产品" prop="productName"></el-table-column>
              <el-table-column label="分组" prop="projectName"></el-table-column>
              <el-table-column label="当前固件版本" prop="firmwareNameCurrent"></el-table-column>
              <el-table-column label="升级目标版本" prop="firmwareNameTarget"></el-table-column>
              <el-table-column label="状态" prop="upgradeStatus">
                <template #default="scope">
                  <span>{{filterStatus(scope.row.upgradeStatus)}}</span>
                </template>
              </el-table-column>
              <el-table-column label="升级时间" prop="upgradeTime">
                <template #default="scope">
                  <span>{{scope.row.upgradeTime ? moment(scope.row.upgradeTime).format('YYYY-MM-DD HH:mm:ss') : ''}}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" fixed="right">
                <template #default="scope">
                  <el-link class="table-btn" type="primary" :underline="false" @click="handleUpdate(scope.row)">升级</el-link>
                  <el-link class="table-btn" type="primary" :underline="false" @click="handleLog(scope.row)">升级日志</el-link>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="page-right-block">
            <el-pagination
              class="nr-page"
              v-model:current-page="searchParams.currentPage"
              v-model:page-size="searchParams.pageSize"
              :page-sizes="[10, 20, 30, 40]"
              background
              layout="total, prev, pager, next, sizes, jumper"
              :total="searchParams.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange">
            </el-pagination>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <firmware-update-log-dialog
      :dialogVisible="updateLogDialogVis"
      :formData="firmwareData.data"
      @update:dialogVisible="(value: boolean) => updateLogDialogVis = value">
    </firmware-update-log-dialog>

    <firmware-update-form
      :dialogVisible="modifyFormVis"
      :formData="firmwareUpdateData.data"
      @update:dialogVisible="(value: boolean) => modifyFormVis = value"
      @submit="getFirmwareUpdateData">
    </firmware-update-form>
  </div>
</template>

<script setup lang="ts" name="FirmwareUpdate">
import { ref, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import FirmwareUpdateLogDialog from './firmware-update-log-dialog.vue'
import FirmwareUpdateForm from './firmware-update-form.vue'
import { projectList } from '@/api/project-manage'
import { productList } from '@/api/product-manage'
import { firmwareList } from '@/api/firmware-manage'
import { firmwareUpdateListPage } from '@/api/firmware-update'
import moment from 'moment'

const pageLoading = ref(false)
const defaultProps = {
  children: 'projectTree',
  label: 'projectName',
}
const treeRef = ref<any>(null)
const treeData = ref<any>([])
const productOptions = ref<any>([])
const versionOptions = ref<any>([])
const searchParamsRef = ref<FormInstance>()
const searchParams = reactive({
  product: '',
  version: <any>null,
  device: '',
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const tableData = ref<any>([])
const tableBlockRef = ref<any>(null)
const tableHeight = ref(200)
const updateLogDialogVis = ref(false)
const firmwareData = ref({
  data: {}
})
const firmwareUpdateData = ref({
  data: []
})
const modifyFormVis = ref(false)

onMounted(() => {
  resizeTable()
  window.addEventListener('resize', resizeTable, false)
  getProjectData()
  getProductList()
  // getFirmwareList()
  getFirmwareUpdateData()
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeTable, false)
})

// 窗口改变table高度
const resizeTable = () => {
  tableHeight.value = tableBlockRef.value.offsetHeight
}

// 产品下拉改变事件
const handleChangeProduct = (val: any) => {
  if (val === '') {
    searchParams.version = null
    versionOptions.value = []
  } else {
    getFirmwareList()
  }
}

// 固件下拉清空事件
const handleClearVersion = (val: any) => {
  searchParams.version = -1
}

// 过滤升级状态
const filterStatus = (type: any) => {
  let str = ''
  switch(type) {
    case '-1':
      str = '升级失败'
      break
    case '0':
      str = '升级中'
      break
    case '1':
      str = '升级成功'
      break
    case '2':
      str = '即将升级'
      break
  }
  return str
}

// 查询
const search = () => {
  searchParams.currentPage = 1
  getFirmwareUpdateData()
}

// 重置
const reset = () => {
  versionOptions.value = []
  searchParams.version = null
  searchParamsRef.value?.resetFields()
}

// 分页跳转
const handleCurrentChange = (val: number) => {
  getFirmwareUpdateData()
}
const handleSizeChange = (val: number) => {
  getFirmwareUpdateData()
}

// 批量升级
const batchUpdate = () => {
  let arr = <any>[...multipleTableRef.value?.getSelectionRows()]
  if (arr.length === 0) {
    ElMessage.error(`未选择设备！`)
    return false
  }
  modifyFormVis.value = true
  firmwareUpdateData.value.data = <any>[...arr]
}

// 升级
const handleUpdate = (row: any) => {
  modifyFormVis.value = true
  firmwareUpdateData.value.data = <any>[row]
}

// 升级日志
const handleLog = (row: any) => {
  updateLogDialogVis.value = true
  firmwareData.value.data = Object.assign({}, row)
}

// 获取项目树表格数据
const getProjectData = async () => {
  pageLoading.value = true
  await projectList().then((res: any) => {
    if (res.code === 0) {
      treeData.value = [res.data]
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
  pageLoading.value = false
}

// 获取产品列表数据
const getProductList = async () => {
  pageLoading.value = true
  await productList().then((res: any) => {
    if (res.code === 0) {
      productOptions.value = [...res.list]
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
  pageLoading.value = false
}

// 获取固件列表数据
const getFirmwareList = async () => {
  pageLoading.value = true
  let params = {
    productId: searchParams.product
  }
  await firmwareList(params).then((res: any) => {
    if (res.code === 0) {
      searchParams.version = -1
      let arr = []
      for (let i = 0; i < res.list.length; i++) {
        let item = res.list[i]
        arr.push({
          firmwareName: item.firmwareName,
          value: item.firmwareName,
          id: item.id
        })
      }
      versionOptions.value = [{ firmwareName: '全部', value: '', id: -1 }, ...arr]
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
  pageLoading.value = false
}

// 获取固件升级表格数据
const getFirmwareUpdateData = async () => {
  pageLoading.value = true
  let version = ''
  for (let i = 0; i < versionOptions.value.length; i++) {
    if (searchParams.version === versionOptions.value[i].id) version = versionOptions.value[i].value
  }
  let params = {
    pidList: treeRef.value?.getCheckedKeys(),
    productId: searchParams.product,
    firmwareName: version,
    deviceName: searchParams.device,
    currentPage: searchParams.currentPage,
    pageSize: searchParams.pageSize
  }
  await firmwareUpdateListPage(params).then((res: any) => {
    if (res.code === 0) {
      tableData.value = [...res.list]
      searchParams.total = res.page.totalSize
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
  pageLoading.value = false
}
</script>

<style lang="stylus" scoped>
@import '../../style/base.styl'

.firmware-update-page
  height 100%
  .table-block
    top 106px
</style>
